#!/usr/bin/env python3
# _*_ coding:utf-8 _*_


from django.conf import settings


def init_permission(user_obj, request):
    permission_queryset = user_obj.roles.filter(permissions__isnull=False).values(
        "permissions__id",
        "permissions__title",
        "permissions__url",
        "permissions__name",
        "permissions__pid_id",
        "permissions__pid__title",
        "permissions__pid__url",
        "permissions__menu_id",
        "permissions__menu__title",
        "permissions__menu__icon__title",
        "permissions__menu__index",
    ).distinct()
    permission_dict = {}
    menu_dict = {}

    for item in permission_queryset:
        permission_dict[item['permissions__name']] = {
            'id': item['permissions__id'],
            'title': item['permissions__title'],
            'url': item['permissions__url'],
            'pid': item['permissions__pid_id'],
            'pid_title': item['permissions__pid__title'],
            'pid_url': item['permissions__pid__url'],
        }
        menu_id = item['permissions__menu__index']
        if not menu_id:
            continue
        node = {
            'id': item['permissions__id'],
            'title': item['permissions__title'],
            'url': item['permissions__url'],
        }
        if menu_id in menu_dict:
            menu_dict[menu_id]['children'].append(node)
        else:
            menu_dict[menu_id] = {
                'id': item['permissions__menu_id'],
                'title': item['permissions__menu__title'],
                'icon': item['permissions__menu__icon__title'],
                'children': [node, ]
            }
    request.session[settings.PERMISSION_SESSION_KEY] = permission_dict
    request.session[settings.MENU_SESSION_KEY] = menu_dict
